package com.wmada.toolkit.common;

/**
 * The type Name utils.
 */
@SuppressWarnings("unused")
public class NameUtils {

    private static final char SEPARATOR = '_';

    /**
     * To underline string.
     *
     * @param s the s
     * @return the string
     */
    public static String toUnderline(String s) {
        if (s == null) {
            return null;
        }
        StringBuilder sb        = new StringBuilder();
        boolean       upperCase = false;
        for (int i = 0; i < s.length(); i++) {
            char    c             = s.charAt(i);
            boolean nextUpperCase = true;
            if (i < (s.length() - 1)) {
                nextUpperCase = Character.isUpperCase(s.charAt(i + 1));
            }
            if (Character.isUpperCase(c)) {
                if (!upperCase || !nextUpperCase) {
                    if (i > 0) {
                        sb.append(SEPARATOR);
                    }
                }
                upperCase = true;
            } else {
                upperCase = false;
            }
            sb.append(Character.toLowerCase(c));
        }
        return sb.toString();
    }

    /**
     * To camel case string.
     *
     * @param s the s
     * @return the string
     */
    public static String toCamelCase(String s) {
        return toCamelCase(s, false);
    }

    /**
     * To camel case string.
     *
     * @param s          the s
     * @param upperFirst the upper first
     * @return the string
     */
    public static String toCamelCase(String s, boolean upperFirst) {
        if (s == null) {
            return null;
        }
        s = s.toLowerCase();
        StringBuilder sb        = new StringBuilder(s.length());
        boolean       upperCase = upperFirst;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c == SEPARATOR) {
                upperCase = true;
            } else if (upperCase) {
                sb.append(Character.toUpperCase(c));
                upperCase = false;
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }

}
